﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NAnt.Core.Attributes;
using System.IO;
using System.Text.RegularExpressions;
using NAnt.Core;

namespace UofCASE.AgileProductLinerDSL.Nant
{
    class AspenConfigurationGenerator : Task
    {

        /*
         *  <AspenConfigurationGenerator 
         *      configurationFile="C:\path\to\file.xml" 
         *      outputDir="C:\path\to\output\" 
         *      featureModel="c:\path\to\model.fm"
         *      />
         */

        [TaskAttribute("configurationFile", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public String ConfigurationFile { get; set; }

        [TaskAttribute("outputDir", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public String OutputDir { get; set; }

        [TaskAttribute("featureModel", Required = true)]
        [StringValidator(AllowEmpty = false)]
        public String FeatureModel { get; set; }

        protected override void ExecuteTask()
        {
            StringBuilder buf = new StringBuilder();
            buf.Append(header());
            foreach (KeyValuePair<String, String> pair in implementingKlassesIncludedInConfiguration())
            {
                buf.Append("\t\t\tBind<" + pair.Key + ">().To<" + pair.Value + ">();\n");
            }
            buf.Append(footer());
            File.WriteAllText(OutputDir + "/" + formattedName() + ".cs", buf.ToString());
        }

        private IEnumerable<KeyValuePair<String, String>> implementingKlassesIncludedInConfiguration()
        {
            IList<KeyValuePair<String, String>> ret = new List<KeyValuePair<String,String>>();

            return ret;
        }

        private string formattedName()
        {
            String name = new FileInfo(FeatureModel).Name;
            Regex regex = new Regex("[-_ \\.]+([a-z])");
            name = regex.Replace(name, new MatchEvaluator(matchEval));
            return name;
        }

        private String matchEval(Match m){
            return m.Groups[1].Value.ToUpper();
        }


        private string header()
        {
            return @"using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;
using Ninject.Modules;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace NinjectSpike
{
    public class " + formattedName() + @" : NinjectModule {
        public override void Load() {";
        }

        private string footer()
        {
            return @"
        }
    }
  
}";
        }

    }
}
